<script setup>
import { ref } from "vue";
import {
  addArticleChannelService,
  updateArticleChannelService,
} from "@/api/article";
import { ElMessage } from "element-plus";

const emit = defineEmits(["success"]);
const isOpen = ref(false);
const formData = ref({
  cate_name: "",
  cate_alias: "",
});
const open = (row) => {
  isOpen.value = true;
  formData.value = { ...row };
};
const form = ref();
const onSubmit = () => {
  form.value.validate(async (valid) => {
    if (valid) {
      if (formData.value.id) {
        await updateArticleChannelService(formData.value);
        ElMessage.success("更新成功！");
      } else {
        await addArticleChannelService(formData.value);
        ElMessage.success("添加成功！");
      }
      isOpen.value = false;
      emit("success");
    }
  });
};
const rules = {
  cate_name: [
    { required: true, message: "分类名字不可以为空！", trigger: "blur" },
    {
      pattern: /^\S{1,10}$/,
      message: "别名必须为1-10之间的非空字符串",
      trigger: "blur",
    },
  ],
  cate_alias: [
    { required: true, message: "分类别名不可以为空！", trigger: "blur" },
    {
      pattern: /^[a-zA-Z0-9]{1,15}$/,
      message: "别名必须为1-15之间的非空字符串",
      trigger: "blur",
    },
  ],
};

defineExpose({
  open,
});
</script>

<template>
  <el-dialog v-model="isOpen" title="添加文章类别" width="500">
    <el-form
      :model="formData"
      :rules="rules"
      style="padding: 0 30px"
      ref="form"
    >
      <el-form-item label="文章别名" prop="cate_alias">
        <el-input v-model="formData.cate_alias"></el-input>
      </el-form-item>
      <el-form-item label="文章名字" prop="cate_name">
        <el-input v-model="formData.cate_name"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="isOpen = false">取消</el-button>
        <el-button type="primary" @click="onSubmit"> 提交 </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss"></style>
